package cn.iocoder.yudao.module.shop.controller.admin.appointment;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.shop.api.appointment.AppointmentApi;
import cn.iocoder.yudao.module.shop.api.appointment.AppointmentApiImpl;
import cn.iocoder.yudao.module.shop.api.appointment.dto.AppointmentCancelReqDTO;
import cn.iocoder.yudao.module.shop.api.appointment.dto.AppointmentCreateReqDTO;
import cn.iocoder.yudao.module.shop.controller.admin.appointment.vo.*;
import cn.iocoder.yudao.module.shop.controller.admin.item.vo.ShopItemCreateReqVO;
import cn.iocoder.yudao.module.shop.controller.admin.order.vo.ShopOrderRespVO;
import cn.iocoder.yudao.module.shop.convert.appointment.AppointmentConvert;
import cn.iocoder.yudao.module.shop.dal.dataobject.order.ShopOrderDO;
import cn.iocoder.yudao.module.shop.dal.mysql.order.ShopOrderMapper;
import cn.iocoder.yudao.module.shop.service.order.ShopOrderService;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.dal.mysql.user.AdminUserMapper;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import com.alipay.api.domain.Shop;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import cn.iocoder.yudao.module.shop.config.shop;

@Tag(name = "管理后台 - 店内预约")
@RestController
@RequestMapping("/shop/appointment")
@Validated
public class AppointmentController {

    @Resource
    private AppointmentApi appointmentApi;

    @Resource
    private ShopOrderService shopOrderService;

    @Resource
    private AdminUserMapper adminUserMapper;

    @Resource
    private ShopOrderMapper shopOrderMapper;

    @GetMapping("/config")
    @Operation(summary = "预约配置")
    @PreAuthorize("@ss.hasPermission('shop:order:create')")
    public CommonResult<AppointmentConfigRespVO> getConfig() {
        AppointmentConfigRespVO appointmentConfigRespVO = new AppointmentConfigRespVO();
        appointmentConfigRespVO.setHour(shop.HOUR);
        appointmentConfigRespVO.setMinute(shop.MINUTE);
        appointmentConfigRespVO.setInterval(shop.INTERVAL);
        appointmentConfigRespVO.setIndexCount(shop.INDEX_COUNT);
        return success(appointmentConfigRespVO);
    }

    @PostMapping("/create")
    @Operation(summary = "店内预约")
    @PreAuthorize("@ss.hasPermission('shop:order:create')")
    public CommonResult<Long> createAppointment(@Valid @RequestBody AppointmentCreateReqVO createReqVO) {
        AppointmentCreateReqDTO appointmentCreateReqDTO = AppointmentConvert.INSTANCE.convert(createReqVO);
        return success(appointmentApi.createAppointment(appointmentCreateReqDTO));
    }

    @PostMapping("/cancel")
    @Operation(summary = "取消预约")
    @PreAuthorize("@ss.hasPermission('shop:order:update')")
    public CommonResult<Boolean> cancelAppointment(@Valid @RequestBody AppointmentCancelReqVO cancelReqVO) {
        AppointmentCancelReqDTO appointmentCancelReqDTO = AppointmentConvert.INSTANCE.convert(cancelReqVO);
        return success(appointmentApi.cancelAppointment(appointmentCancelReqDTO));
    }

    @PostMapping("/validate")
    @Operation(summary = "可预约时间段")
    public CommonResult<AppointmentValidateRespVO> validateAppointment(@Valid @RequestBody AppointmentValidateReqVO validateReqVO) {
        LocalDate today = LocalDate.now();
        LocalDateTime zeroToday = LocalDateTime.of(today, LocalTime.MIN);

        List<AdminUserDO> userList = null;
        // 今天以后的只约在职艾灸师
        // 今天以前的所有艾灸师，因为会有离职了灸过的
        if(validateReqVO.getDateTime().compareTo(zeroToday) > 0){
            userList = adminUserMapper.selectList(new LambdaQueryWrapperX<AdminUserDO>()
                    .eq(AdminUserDO::getStatus, CommonStatusEnum.ENABLE)
                    .eq(AdminUserDO::getTenantId, validateReqVO.getTenantId()));
        }else {
            userList = adminUserMapper.selectList(AdminUserDO::getTenantId, validateReqVO.getTenantId());
        }

        Map<Long, AdminUserDO> userMap = CollectionUtils.convertMap(userList, AdminUserDO::getId);

        List<ShopOrderRespVO> orderList = shopOrderService.getOrderList(validateReqVO.getDateTime(), validateReqVO.getTenantId());
        Map<Long, List<ShopOrderRespVO>> orderListMap = CollectionUtils.convertMultiMap(orderList, ShopOrderRespVO::getUserId);

        return success(AppointmentConvert.INSTANCE.convert(userMap, orderListMap));
    }
}
